<script lang="ts" setup>
import { ref, onMounted } from 'vue'
const props = withDefaults(
  defineProps<{
    loading: boolean
    finished: boolean
  }>(),
  {
    loading: false,
    finished: false
  }
)
const emit = defineEmits<{
  (el: 'infinite'): void
}>()

const target = ref<HTMLElement>()
onMounted(() => {
  const observe = new IntersectionObserver(([{ intersectionRatio }]) => {
    if (intersectionRatio) {
      // 判断是否加载完毕且数据未加载完毕
      if (props.loading === false && props.finished === false) {
        emit('infinite')
      }
    }
  })
  // 开始监听元素
  if (target.value) observe.observe(target.value)
})
</script>

<template>
  <div class="xtx-infinite-loading" ref="target">
    <div class="loading" v-if="loading">
      <span class="img"></span>
      <span class="text">正在加载...</span>
    </div>
    <div class="none" v-if="finished">
      <span class="img"></span>
      <span class="text">亲，没有更多了</span>
    </div>
  </div>
</template>

<style scoped lang="less">
.xtx-infinite-loading {
  .loading {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200px;
    .img {
      width: 50px;
      height: 50px;
      background: url(../../assets/images/load.gif) no-repeat center /
        contain;
    }
    .text {
      color: #999;
      font-size: 16px;
    }
  }
  .none {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200px;
    .img {
      width: 200px;
      height: 134px;
      background: url(../../assets/images/none.png) no-repeat center /
        contain;
    }
    .text {
      color: #999;
      font-size: 16px;
    }
  }
}
</style>
